<script lang="ts" setup>
import {
  getEditingProject,
  updateEditingProject,
  submitMediaProducingJob
} from '@/api/creative/smart-media/production'
import { getTemplateMaterials } from '@/api/creative/smart-media/template-manager'
import { batchGetMediaInfos } from '@/api/creative/smart-media/media-manager'
import SearchMedia from './components/search-media.vue'
import './aliyun-advanced-template-sdk/index'
import './aliyun-advanced-template-sdk/index.css'
import { ElMessage, ElMessageBox } from 'element-plus'
import ProduceVideo from '@/views/creative/smart-media/components/produce-video.vue'

declare const AliyunAdvancedTemplate: any

const router = useRouter()

const projectId = router.currentRoute.value.query.projectId as string

const searchMediaRef = ref<InstanceType<typeof SearchMedia>>()
const produceVideoRef = ref<InstanceType<typeof ProduceVideo>>()

// 一个将对象中所有key转换为大写开头的函数，包含嵌套对象
const toUpperCase = (obj) => {
  const newObj = {}
  Object.keys(obj).forEach((key) => {
    const newKey = key[0].toUpperCase() + key.slice(1)
    // 数组
    if (Array.isArray(obj[key])) {
      newObj[newKey] = obj[key].map((item) => {
        if (typeof item === 'object' && item !== null) {
          return toUpperCase(item)
        }
        return item
      })
    } else if (typeof obj[key] === 'object' && obj[key] !== null) {
      newObj[newKey] = toUpperCase(obj[key])
    } else {
      newObj[newKey] = obj[key]
    }
  })
  return newObj
}

onMounted(() => {
  AliyunAdvancedTemplate.init({
    locale: 'zh-CN',
    container: document.getElementById('aliyun-advanced-template'),
    projectId,
    onBackButtonClick: () => {
      // 跳转回列表页
      router.back()
    },
    updateEditingProject: async (data: {
      ProjectId: string
      Title?: string
      TemplateId?: string
      ClipsParam?: string
    }) => {
      const res = await updateEditingProject({
        projectId: data.ProjectId,
        title: data.Title,
        templateId: data.TemplateId,
        clipsParam: data.ClipsParam
      })

      ElMessage.success('保存成功')

      return {
        successResponse: true,
        data: toUpperCase(res)
      }
    },
    getEditingProject: async ({ ProjectId }) => {
      const res = await getEditingProject({
        projectId: ProjectId,
        requestSource: 'WebSDK'
      })
      console.log('🚀 ~ file: advanced-template-editor.vue:71 ~ getEditingProject: ~ res:', res)

      return {
        successResponse: true,
        data: toUpperCase(res)
      }
    },
    getTemplateMaterials: async (data: { TemplateId: string; FileList: string }) => {
      const res = await getTemplateMaterials({
        templateId: data.TemplateId,
        fileList: data.FileList
      })
      console.log('🚀 ~ file: advanced-template-editor.vue:83 ~ getTemplateMaterials: ~ res:', res)

      return {
        successResponse: true,
        data: toUpperCase(res)
      }
    },
    batchGetMediaInfos: async (data: { AdditionType: 'FileInfo'; MediaIds: string }) => {
      const res = await batchGetMediaInfos({
        additionType: data.AdditionType,
        mediaIds: data.MediaIds
      })
      console.log('🚀 ~ file: advanced-template-editor.vue:95 ~ batchGetMediaInfos: ~ res:', res)

      return {
        successResponse: true,
        data: toUpperCase(res)
      }
    },
    onChangeMaterial: async () => {
      const mediaInfos = (await searchMediaRef.value?.open({ multiple: false })) as any[]

      console.log('mediaInfos[0]', toUpperCase(mediaInfos[0]))

      return toUpperCase(mediaInfos[0])
    },
    onConfirmPreview: ({ ProjectTitle, TemplateId, TemplateSize, ClipsParam }) => {
      const height = 360 // 假设按照 360P 进行预览
      let width = Math.floor((height / TemplateSize[1]) * TemplateSize[0]) // 根据模板的比例算出宽度

      if (width % 2 === 1) width += 1 // 保证宽度是偶数

      const filename = `${encodeURIComponent(ProjectTitle)}_preview_${new Date().toISOString()}.mp4` // 预览视频文件名由您自定义，这里只是一种示例

      const outputMediaConfig = JSON.stringify({
        MediaURL: `https://exampleBucket.oss-exampleRegion.aliyuncs.com/examplePath/${filename}`,
        Width: width,
        Height: height
      })

      submitMediaProducingJob({
        projectId,
        templateId: TemplateId,
        clipsParam: ClipsParam,
        outputMediaConfig
      })
    },
    submitMediaProducingJob: async (data) => {
      const { TemplateId, TemplateSize, ClipsParam } = data

      const formValues = (await produceVideoRef.value?.open(data)) as any
      console.log('formValues', formValues)
      const res = await submitMediaProducingJob({
        // projectId,
        templateId: TemplateId,
        clipsParam: ClipsParam,
        outputMediaConfig: JSON.stringify({
          MediaURL: `https://md-test-001.oss-cn-hangzhou.aliyuncs.com/ice-generated/${formValues.fileName}.${formValues.format}`
        })
      })

      ElMessageBox.alert('提交任务成功，请前往“素材管理”页面查看结果。', '提交成功', {
        confirmButtonText: '确定',
        callback: () => {}
      })

      // return new Promise((resolve, reject) => {
      //   // 假设 showSubmitModal 是您编写的一个函数，这个函数将展示一个 modal 组件，modal 中提供表单供用户填写合成信息
      //   // 比如文件名、存储路径、格式、分辨率等，当用户提交表单时，这些填写的信息将被整理成 formValues 传入 onOk 里
      //   showSubmitModal({
      //     onOk: async (formValues) => {
      //       const res = await request('SubmitMediaProducingJob', {
      //         ...formValues,
      //         ProjectId: projectId,
      //         TemplateId,
      //         ClipsParam
      //       })
      //       if (res.code === '200') {
      //         console.log('success')
      //         resolve()
      //       } else {
      //         console.error('failed')
      //         reject()
      //       }
      //     }
      //   })
      // })
    }
  })
})
</script>

<template>
  <div class="absolute top-4 left-4 right-4 bottom-4 bg-blue-300">
    <!-- 剪辑工具挂载div -->
    <div id="aliyun-advanced-template" class="w-full h-full"></div>

    <!-- 搜索媒资弹窗 -->
    <SearchMedia ref="searchMediaRef" />

    <!-- 视频合成表单弹窗 -->
    <ProduceVideo ref="produceVideoRef" />
  </div>
</template>

<style scoped></style>
